package lv.ante.dziesmas;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LilyParser {

	private static final String TWO_SCORES = "\\\\score {\n"
			+ "\\\\fullScore\n"
			+ "\\\\header { piece = \"__\" opus = \"__\" }\n"
			+ "}\n"
			+ "\\\\markup { \\\\with-color #(x11-color 'gray80) \\\\sans \\\\smaller \"dziesmas.ante.lv\" }\n"
			+ "\\\\score {\n" + "\\\\unfoldRepeats\n" + "\\\\fullScore\n"
			+ "\\\\midi {\n"
			+ "\\\\context { \\\\Staff \\\\remove \"Staff_performer\" }\n"
			+ "\\\\context { \\\\Voice \\\\consists \"Staff_performer\" }\n" + "}\n"
			+ "}\n";

	public static void main(String[] args) throws IOException {
		if (args.length < 2) {
			System.err.println("Usage: java lv.ante.dziesmas.LilyParser file.ly newfile.ly");
			System.exit(0);
		}
		String content = SVGParser.getFileAsString(args[0]);
//		System.err.println("File is " + args[0]);
		
		Pattern p1 = Pattern.compile("left-margin\\s*=\\s*[0-9\\.]+\\\\cm");
		Matcher m1 = p1.matcher(content);
		if (!m1.find()) {
			System.err.println("Could not find left-margin element");
		}
		String content1 = m1.replaceFirst("left-margin = 0.4\\\\cm");
		
//		Pattern p2 = Pattern.compile("\\\\score\\s*\\{\\s*<<([.\\n]*)>>%\\\\midi\\s*\\{\\s*\\}\\s*\\}", Pattern.MULTILINE);
		Pattern p2 = Pattern.compile("\\\\score\\s*\\{\\s*<<((.|\\n)*)>>[\\s\\n]*%\\\\midi\\s*\\{\\s*\\}[\\s\\n]*\\}", Pattern.MULTILINE);
		Matcher m2 = p2.matcher(content1);
		if (!m2.find()) {
			System.err.println("Could not find score element");
		}
		String content2 = m2.replaceFirst("fullScore = <<$1>>\n\n" + TWO_SCORES);
		
		FileOutputStream fos = new FileOutputStream(args[1]);
		OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
		BufferedWriter bw = new BufferedWriter(osw);
		
		bw.write(content2);
		bw.newLine();
		
		bw.close();
		osw.close();
		fos.close();
	}
}
